-module(sys_mon_evt).
-behaviour(gen_event).
-export([start_link/0, init/1,handle_event/2,handle_call/2,handle_info/2,terminate/2,code_change/3]).
-export([do/3]).
-include("protocol.hrl").
-include("management.hrl").
-define(SERVER,?MODULE).

do(server_list,Cond,ethml) ->
	{
	table,[],
		lists:map(fun(Item) ->
					{tr,[],[{td,[],ui_util:link_to_pid(Item#server_rec.pid)},
							{td,[],Item#server_rec.title},
							{td,[],Item#server_rec.type}]}
				  end
				  ,do(server_list,Cond,obj))
	};
	
	
do(server_list,_Cond,obj) ->
	try
		gen_event:call(?SERVER,?MODULE,list)
	catch
		_ ->
			[]
	end.
start_link() ->
	{ok,Pid} = gen_event:start_link({local,?SERVER}),
	gen_event:add_handler(?SERVER,?MODULE,[]),
	{ok,Pid}.
init([]) ->
	io:format("register the event"),
	{ok,[]}.
handle_event({up,{Pid,Title,Type}},List) ->
	Server = #server_rec{pid = Pid,title = Title,type = Type},
	{ok,[Server|List]};
handle_event({down,Pid},List) ->
	{ok,delete_server(Pid,List)};
handle_event(Event,State) ->
	io:format("recevied the event ~p~n",[Event]),
	{ok,State}.
handle_call(list,S_List) ->
	{ok,S_List,S_List};
handle_call(_Request,State) ->
	{ok,ok,State}.
handle_info(_Info,State) ->
	{ok,State}.
terminate(Reason,_State) ->
	io:format("terminte with ~p ~n",[Reason]), 
	ok.
code_change(_, State, _) ->
	{ok,State}.
	
dump_server(_,[]) ->
	"empty";
dump_server(text,List) when is_list(List) ->
	lists:map(fun(Item) -> dump_server(text,Item) end, List);
	
dump_server(text,Item) when is_record(Item,server_rec) ->
	io_lib:format("~p dump~n",[Item]).
	
delete_server(Pid,List) ->
	delete_serverA([],Pid,List).
delete_serverA(Res,Pid,[]) ->
	Res;
delete_serverA(Res,Pid,[S|Other]) when S#server_rec.pid =:= Pid ->
	delete_serverA(Res,Pid,Other);
delete_serverA(Res,Pid,[S|Other]) when S#server_rec.pid =/= Pid ->
	delete_serverA([S|Res],Pid,Other).


